<template>
    <div style="margin-right:6px;">
        <!-- 预览弹窗 -->
        <el-dialog
            :title="`${fileInfo.name}`" 
            v-model="visible"
            :append-to-body="true"
            :destroy-on-close="true"
            :style="{'width':'auto'}"
        >
            <div>
                <!-- 默认预览图片文件 -->
                <div v-if="checkIsImg(fileInfo.name)" style="text-align:center;">
                    <img :src="getFullPath(fileInfo.url)"  />
                </div>           
                <!-- 预览pdf类型 -->
               
            </div>
            <template #footer>
                <div class="dialog-footer">
                  <el-button @click="handleClose">关闭</el-button>
                </div>
            </template>
        </el-dialog>
        <el-upload 
            :file-list="fileList"
            list-type="picture-card" 
            :limit="maxNumber"
            :class="{ myUpload:true, hide:hide, rect: size === 'rect', small: size === 'small', mini: size === 'mini', large: size === 'large' }" 
            :action="uploadURL + '/file/upload/allFileUpload'"
            :before-upload="beforeUpload" 
            :on-success="handleSuccess"
            :disabled="noAction"
        >
            <template #file="{ file }">
                <div style="text-align:center;width:100%;">
                    <video v-if="checkIsVideo(file.name, file)" style="width:100%; height:100%;">
                        <source :src="file.url" />
                    </video>
                    <img v-else class="el-upload-list__item-thumbnail" style="width:75%;" :src="getFileThumb(file)" alt="" />
                    <div class="myUpload-file-title" :class="{ 'marquee': file.name && file.name.length > 12 && marquee ? true : false }"
                    >{{ file.name }}</div>
                    <span v-if="!noAction" class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </span>
                    </span>
                    <span v-else class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-delete" @click="handlePreview(file)">
                            <el-icon>
                                <ZoomIn />
                            </el-icon>
                        </span> 
                    </span>
                </div>
            </template>
            <template #default>
                <div style="display:flex; flex-direction: column; justify-content: center; align-items:center;">
                    <el-icon style="font-size:48px; color:#409eff; "><UploadFilled /></el-icon>
                    <div>{{ `上传${ text2 ? text2 : fileType === 'img' ? '图片' : ( fileType === 'word' || fileType === 'pdf' ) ? '文档' : fileType === 'video' ? '视频' : ''}`
                    }}</div>
                </div>
            </template>
            
        </el-upload>
        <div style="font-size:0.8rem; color:rgba(0, 0, 0, 0.65); display:flex; align-items: center; margin:8px 0;">
            <el-icon v-if="text" :size="16" style="margin-right:6px;"><Warning /></el-icon>
            <span>{{ text || '' }}</span>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, computed, reactive, onMounted, nextTick } from 'vue';
import { Plus, Delete, ZoomIn, UploadFilled, Warning } from '@element-plus/icons-vue';
import { ElMessage, ElLoading } from 'element-plus';
import { getFullPath } from '@/api/tpl.js';
import excelIcon from '@/assets/excel-icon.png';
import pdfIcon from '@/assets/pdf-icon.png';
import pptIcon from '@/assets/ppt-icon.png';
import videoIcon from '@/assets/video-icon.png';
import wordIcon from '@/assets/word-icon.png';
import { uploadURL } from '@/utils/axios.ts'; 

const fileInfo = ref({});
const fileList = ref([]);
const visible = ref(false);

const videoTypes = ['mp4', 'ogg', 'flv', 'avi', 'wmv'];
const imgTypes = ['jpg', 'jpeg', 'png'];
const fileTypes = {
    'doc': wordIcon,
    'docx': wordIcon,
    'xls': excelIcon,
    'xlsx': excelIcon,
    'pdf': pdfIcon,
    'ppt': pptIcon,
    'pptx': pptIcon,
    'mp4': videoIcon,
    'ogg': videoIcon,
    'flv': videoIcon,
    'avi': videoIcon,
    'wmv': videoIcon
}

const props = defineProps({
    text: String,
    text2:null,
    fileType: String,
    size: String,
    forIcon: Boolean,
    prop: String,
    noAction:{ type:Boolean, default:false },
    maxSize: { type: Number, default: 5 },
    maxNumber:{ type:Number, default:1 },
    allowTypes:{ type:Array, default:[] },
    marquee:{ type:Boolean, default:true }
});
const emit = defineEmits(['on-select']);

function init(filePath){
    if (filePath && typeof filePath === 'string') {
        // 截取文件名
        let trimArr = filePath.split(';').filter(i=>i);    
        let newArr = [];
        trimArr.forEach(path=>{
            let temp = path.split('_');
            let fileName = temp.length > 1 ? temp[temp.length - 1] : '';
            newArr.push({ name: fileName, url:path });  
        });      
        fileList.value = newArr;
    }
}
function clear(){
    fileList.value = [];
}
defineExpose({
    init,
    clear,
    fileList
})
function checkIsVideo(name, file){
    console.log('file...', file);
    let temp = name ? name.split('.') : '';
    let type = temp.length > 1 ? temp[temp.length - 1] : '';
    return videoTypes.includes(type);
}
function checkIsImg(name){
   
    let temp = name ? name.split('.') : '';
    let type = temp.length > 1 ? temp[temp.length - 1] : '';
     
    return type === 'jpeg' || type === 'jpg' || type === 'gif' || type === 'png';
}
const getFileThumb = file => {
    let temp = file.name.split('.');
    let type = temp.length > 1 ? temp[temp.length - 1] : '';
    // 根据文件名判断文件类型
    return fileTypes[type] ||  ( file.url.includes('http') || file.url.includes('https') ? file.url : getFullPath(file.url) );
}
const beforeUpload = (file) => {
    let strArr = file.name.split('.');
    let type = strArr[strArr.length - 1];
    return new Promise((resolve, reject)=>{
        if ( props.allowTypes.includes(type)) {
            if ( file.size / 1024 / 1024 < props.maxSize ) {
                resolve();
            } else {
                ElMessage.error('文件过大');
                reject();
            }
        } else {
            ElMessage.error('文件类型不匹配');
            reject();
        }
    })
    
    // if ( props.fileType === 'pdf') {
    //     return new Promise((resolve, reject)=>{
    //         let less20mb = file.size / 1024 / 1024 < 20;
    //         if (type !== 'pdf') {
    //             ElMessage.error('只能上传pdf文件');
    //             reject();
    //         }
    //         if (!less20mb) {
    //             ElMessage('文件不能超过20mb');
    //             reject();
    //         }
    //         resolve();
    //     })
    // } else if (props.fileType === 'word') {
    //     return new Promise((resolve, reject) => {
    //         let less10mb = file.size / 1024 / 1024 < 10;
    //         if (type !== 'doc' && type !== 'docx') {
    //             ElMessage.error('只能上传word文件');
    //             reject();
    //         }
    //         if (!less10mb) {
    //             ElMessage('文件不能超过10mb');
    //             reject();
    //         }
    //         resolve();
    //     })
    // } else if (props.fileType === 'img') {
    //     return new Promise((resolve, reject) => {
    //         const isJPG = type === 'jpeg';
    //         const isJPEG = type === 'jpg';
    //         const isGIF = type === 'gif';
    //         const isPNG = type === 'png';
    //         const less500K = file.size / 1024 / 1024 < 1;
    //         if (!(isJPG || isJPEG || isGIF || isPNG)) {
    //             ElMessage.error('只能上传JPG 、JPEG 、GIF、 PNG格式的图片');
    //             reject();
    //         }
    //         if (!less500K) {
    //             ElMessage.error('图片不能超过1mb');
    //             reject();
    //         }
    //         resolve();
    //         // if (props.forIcon) {
    //         //     const reader = new FileReader();
    //         //     reader.readAsDataURL(file);
    //         //     reader.onload = () => {
    //         //         let image = new Image();
    //         //         image.src = reader.result;
    //         //         image.onload = () => {
    //         //             if (image.width === 48 && image.height === 48) {
    //         //                 resolve();
    //         //             } else {
    //         //                 ElMessage.error('尺寸必须为48px * 48px');
    //         //                 reject();
    //         //             }
    //         //         }
    //         //     }
    //         // } else {
    //         //     resolve();
    //         // }
    //     })
    // } else if (props.fileType === 'video') {
    //     return new Promise((resolve, reject) => {
    //         const isMP4 = file.type === 'video/mp4';
    //         const isOGG = file.type === 'video/ogg';
    //         const isFLV = file.type === 'video/flv';
    //         const isAVI = file.type === 'video/avi';
    //         const isWMV = file.type === 'video/wmv';
    //         const less500K = file.size / 1024 / 1024 < 100;
    //         if (!(isMP4 || isOGG || isFLV || isAVI || isWMV)) {
    //             ElMessage.error('只能上传mp4/ogg/flv/avi/wmv格式的视频');
    //             reject();
    //         }
    //         if (!less500K) {
    //             ElMessage.error('视频不能超过100MB');
    //             reject();
    //         }
    //         resolve();
    //     })
    // }
}

const handleRemove = ( file ) => {
    fileList.value = fileList.value.filter(i=>i.uid !== file.uid );    
}
const handlePreview = ( file )=>{
    // console.log('preview', file);
    fileInfo.value = file;
    visible.value = true;
}
const handleClose = ()=>{
    fileInfo.value = {};
    visible.value =  false;
}
const handleSuccess = (response, uploadFile) => {
    // 资源上传成功将路径传递给父组件的状态
    // console.log(uploadFile);
    let path = response.data.length ? response.data[0].logoPath : '';
    fileList.value.push({ uid:uploadFile.uid, name:uploadFile.name, url:path, originFile:uploadFile.raw });
}
watch(()=>fileList.value.length, ()=>{
    // console.log('fileList...', fileList.value);
    emit('on-select', props.prop, fileList.value.map(i=>i.url).join(';') );
})
const hide = computed(()=>{
    
    return fileList.value.length >= props.maxNumber
})

</script>

<style>

.myUpload .el-upload-list.el-upload-list--picture-card {
    flex-wrap:nowrap;
}
.hide .el-upload.el-upload--picture-card {
    display: none;
}
.myUpload .myUpload-file-title {
    white-space:nowrap;
    width:100%;  
    position:absolute; 
    font-size:14px;
    line-height:14px; 
    bottom:2px; 
}
.myUpload .myUpload-file-title.marquee {
    animation: marquee 6s linear infinite;
}
.small .el-upload--picture-card {
    width: 90px;
    height: 90px;
}

.small .el-upload-list .el-upload-list__item {
    width: 90px;
    height: 90px;
}
.mini .el-upload--picture-card {
    width: 60px;
    height: 60px;
}

.mini .el-upload-list .el-upload-list__item {
    width: 60px;
    height: 60px;
}
.large .el-upload--picture-card {
    width: 340px;
    height: 200px;
}
.large .el-upload-list .el-upload-list__item {
    width: 340px;
    height: 200px;
}
.rect .el-upload--picture-card {
    width: 260px;
    height: 90px;
}

.rect .el-upload-list .el-upload-list__item {
    width: 260px;
    height: 90px;
}
@keyframes marquee {
    0% { transform: translateX(100%); }
    100% { transform: translateX(-100%); }
}
</style>
